<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>小程序奇技淫巧之页面跳转管理 | 被删的前端游乐场</title>
    <meta name="generator" content="VuePress 1.8.2">
    
    <meta name="description" content="Just playing around">
    
    <link rel="preload" href="/front-end-playground/assets/css/0.styles.6ad2a9ca.css" as="style"><link rel="preload" href="/front-end-playground/assets/js/app.1e2670bf.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/2.38d016d1.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/3.e3f029cb.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/186.32496fdc.js" as="script">
    <link rel="stylesheet" href="/front-end-playground/assets/css/0.styles.6ad2a9ca.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/front-end-playground/" class="home-link router-link-active"><!----> <span class="site-name">被删的前端游乐场</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/front-end-playground/" class="nav-link">概述</a></div><div class="nav-item"><a href="/front-end-playground/front-end-basic/" class="nav-link">前端领域</a></div><div class="nav-item"><a href="/front-end-playground/vue/" class="nav-link">Vue学习</a></div><div class="nav-item"><a href="/front-end-playground/wxapp/" class="nav-link router-link-active">小程序学习</a></div><div class="nav-item"><a href="/front-end-playground/front-end-others/" class="nav-link">百家齐放</a></div><div class="nav-item"><a href="/front-end-playground/front-end-addon/" class="nav-link">前端的进击</a></div><div class="nav-item"><a href="/front-end-playground/front-end-work/" class="nav-link">前端与工作</a></div><div class="nav-item"><a href="/front-end-playground/faq.html" class="nav-link">FAQ</a></div> <a href="https://github.com/godbasin/front-end-playground" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/front-end-playground/" class="nav-link">概述</a></div><div class="nav-item"><a href="/front-end-playground/front-end-basic/" class="nav-link">前端领域</a></div><div class="nav-item"><a href="/front-end-playground/vue/" class="nav-link">Vue学习</a></div><div class="nav-item"><a href="/front-end-playground/wxapp/" class="nav-link router-link-active">小程序学习</a></div><div class="nav-item"><a href="/front-end-playground/front-end-others/" class="nav-link">百家齐放</a></div><div class="nav-item"><a href="/front-end-playground/front-end-addon/" class="nav-link">前端的进击</a></div><div class="nav-item"><a href="/front-end-playground/front-end-work/" class="nav-link">前端与工作</a></div><div class="nav-item"><a href="/front-end-playground/faq.html" class="nav-link">FAQ</a></div> <a href="https://github.com/godbasin/front-end-playground" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>小程序原理</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:10px;"><div class="kitty-main" data-v-2b653b36><span class="stand" data-v-2b653b36></span> <div class="cat" data-v-2b653b36><div class="body" data-v-2b653b36></div> <div class="head" data-v-2b653b36><div class="ear" data-v-2b653b36></div> <div class="ear" data-v-2b653b36></div></div> <div class="face" data-v-2b653b36><div class="nose" data-v-2b653b36></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div></div> <div class="tail-container" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36></div></div></div></div></div></div></div></div></div></div> <p class="sidebar-heading open"><span>小程序开发技巧</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-official-functions.html" class="sidebar-link">超实用小程序官方能力</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-gulp.html" class="sidebar-link">小程序 gulp 简单构建</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-typescript.html" class="sidebar-link">小程序+Typescript</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-computed.html" class="sidebar-link">使用 computed 计算属性</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-watch.html" class="sidebar-link">使用 watch 观察属性</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-cloud.html" class="sidebar-link">认识小程序云开发</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-login.html" class="sidebar-link">小程序的登录与静默续期</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-multi-request.html" class="sidebar-link">小程序多页面接口数据缓存</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-global-data-behavior.html" class="sidebar-link">小程序奇技淫巧之globalDataBehavior管理全局状态</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-logs.html" class="sidebar-link">小程序奇技淫巧之日志能力</a></li><li><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-navigate.html" aria-current="page" class="active sidebar-link">小程序奇技淫巧之页面跳转管理</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-navigate.html#页面栈管理" class="sidebar-link">页面栈管理</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-navigate.html#页面间跳转" class="sidebar-link">页面间跳转</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-navigate.html#判断跳转来源" class="sidebar-link">判断跳转来源</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-navigate.html#跳转传参" class="sidebar-link">跳转传参</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-navigate.html#结合-component-自动取参" class="sidebar-link">结合 Component 自动取参</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/wxapp/wxapp-technique/wxapp-navigate.html#参考" class="sidebar-link">参考</a></li></ul></li></ul></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>小程序开发月刊</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><p>小程序页面跳转也是一个很容易踩到坑的开发流程，本文介绍页面跳转相关的一些好用的实践和封装的组件库。</p> <h1 id="小程序页面跳转"><a href="#小程序页面跳转" class="header-anchor">#</a> 小程序页面跳转</h1> <p>一个小程序可以有很多页面，每个页面承载不同的功能，页面之间可以互相跳转。我们知道，小程序分为渲染层和逻辑层，渲染层中包含了多个 WebView，每个 WebView 对应到我们的小程序里就是一个页面 Page，每一个页面都独立运行在一个页面层级上，如图：</p> <p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/wxapp-navigate-1.png" alt=""></p> <h2 id="页面栈管理"><a href="#页面栈管理" class="header-anchor">#</a> 页面栈管理</h2> <p>一个小程序拥有多个页面，我们知道<code>wx.navigateTo</code>可以推入一个新的页面。我们看看小程序示例小程序里，在首页使用2次<code>wx.navigateTo</code>后，页面层级会有三层：</p> <p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/wxapp-17.jpg" alt=""></p> <p>我们把这样的一个页面层级称为页面栈。在小程序中所有页面的路由全部由框架进行管理，框架以栈的形式维护了当前的所有页面。小程序中页面栈最多十层，也就是十个 WebView，如果超过了十个之后，就没法再打开新的页面了。</p> <p>对于每一个新的页面层级，渲染层都需要进行一些额外的准备工作。在小程序启动前，客户端会提前准备好一个页面层级用于展示小程序的首页。除此以外，每当一个页面层级被用于渲染页面，客户端都会提前开始准备一个新的页面层级，使得每次调用<code>wx.navigateTo</code>都能够尽快展示一个新的页面。</p> <h2 id="页面间跳转"><a href="#页面间跳转" class="header-anchor">#</a> 页面间跳转</h2> <p>小程序启动时仅有一个页面层级，而在小程序运行中，页面之间的跳转表现包括这些：</p> <table><thead><tr><th>API</th> <th>页面表现</th> <th>页面栈表现</th></tr></thead> <tbody><tr><td><code>wx.navigateTo</code></td> <td>保留当前页面，跳转到应用内的某个页面</td> <td>创建一个新的页面层级</td></tr> <tr><td><code>wx.navigateBack</code></td> <td>关闭当前页面，返回上一页面或多级页面</td> <td>销毁一个页面层级</td></tr> <tr><td><code>wx.redirectTo</code></td> <td>关闭当前页面，跳转到应用内的某个页面</td> <td>将当前页面层级重新初始化。重新传入页面的初始数据、路径等，视图层清空当前页面层级的渲染结果然后重新渲染页面</td></tr> <tr><td><code>wx.reLaunch</code></td> <td>关闭所有页面，打开到应用内的某个页面</td> <td>销毁所有页面层级，再创建一个新的页面层级</td></tr> <tr><td><code>wx.switchTab</code></td> <td>关闭其他所有非 tabBar 页面，跳转到 tabBar 页面</td> <td>销毁所有非 tabBa 页面层级，打开tabBar页面层级</td></tr></tbody></table> <p>上面提到了 tabBar。除了普通的页面跳转，小程序里还支持配置 tabBar。tabBar 就是类似客户端 APP 底部的 tab 切换，为了获得更好的体验，小程序提供了这样的全局组件，在 app.json 文件中设置 tabBar，因此我们小程序会区分 tabBar 页面和非 tabBar 页面。tabBar 页面之间的切换都只会有一个层级，而跳转到非 tabBar 页面之后，就有了页面层级和页面栈的管理。</p> <h1 id="页面跳转技巧"><a href="#页面跳转技巧" class="header-anchor">#</a> 页面跳转技巧</h1> <p>小程序的 JS 脚本是运行在 JsCore 的线程里，小程序的每个页面各自有一个 WebView 线程进行渲染，所以小程序切换页面时，小程序逻辑层的 JS 脚本运行上下文依旧在同一个 JsCore 线程中。</p> <p>因为在同一个 JsCore 线程中，我们就会有一些问题会遇到，也可以有一些小技巧来处理。</p> <h2 id="判断跳转来源"><a href="#判断跳转来源" class="header-anchor">#</a> 判断跳转来源</h2> <p>由于切换页面后，业务逻辑依然在同一个 JsCore 线程中。因此，即使是小程序页面被关闭 unload 之后，如果有原本在执行的逻辑，会继续执行完毕。</p> <p>在这样的情况下，如果有重定向、跳转等逻辑，在跳转之后后续的逻辑依然会继续执行，这时候如果还有其他的跳转逻辑，可能会导致页面连续跳转，严重的话跳转参数丢书会导致白屏。</p> <p>为了防止用户自行返回等操作，可以添加当前页面的条件判断是否要执行，页面栈可以通过<code>getCurrentPages</code>拿到，例如我们可以添加这样的方法处理：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// 处理是否有当前路由</span>
<span class="token keyword">function</span> <span class="token function">matchOriginPath</span><span class="token punctuation">(</span><span class="token parameter">originPageUrl</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> currentPages <span class="token operator">=</span> <span class="token function">getCurrentPages</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> currentPage <span class="token operator">=</span> currentPages<span class="token punctuation">[</span>currentPages<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>route<span class="token punctuation">;</span>
  <span class="token comment">// 判断是否设置了特定页面才进行跳转</span>
  <span class="token comment">// 如果设置了，判断当前页面是否特定页面，是才跳转</span>
  <span class="token comment">// 用于判断当前页面是否已经被跳转走（用户手动关闭等）</span>
  <span class="token keyword">const</span> isMatch <span class="token operator">=</span> <span class="token operator">!</span>originPageUrl <span class="token operator">||</span> <span class="token punctuation">(</span>originPageUrl <span class="token operator">&amp;&amp;</span> currentPage<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span>originPageUrl<span class="token punctuation">)</span> <span class="token operator">&gt;</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 如果设置了，当页面路径不匹配，则进行报错提示</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>isMatch<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span>
      <span class="token string">&quot;matchOriginPath do not match&quot;</span><span class="token punctuation">,</span>
      <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">currentPage: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>currentPage<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">, originPageUrl: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>originPageUrl<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> isMatch<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>通过这样的检查方式，我们可以通过传参来判断下是否要检查：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">/**
 * 跳转到页面
 * @param {object} url 要跳转的页面地址
 * @param {object} originPageUrl 原始页面地址，用于判断来源是否符合
 */</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">navigateTo</span><span class="token punctuation">(</span><span class="token parameter">url<span class="token operator">:</span> string<span class="token punctuation">,</span> originPageUrl<span class="token operator">?</span><span class="token operator">:</span> string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 不符合源页面条件则不跳转</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">matchOriginPath</span><span class="token punctuation">(</span>originPageUrl<span class="token operator">!</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    logger<span class="token punctuation">.</span><span class="token constant">RUN</span><span class="token punctuation">(</span><span class="token string">&quot;navigateTo&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;originPageUrl != currentPage, return&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span><span class="token punctuation">;</span>
  wx<span class="token punctuation">.</span><span class="token function">navigateTo</span><span class="token punctuation">(</span><span class="token punctuation">{</span> url <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这样，我们跳转的时候可以添加参数，预防页面非预期的跳转：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token function">navigateTo</span><span class="token punctuation">(</span><span class="token punctuation">{</span>url<span class="token operator">:</span> <span class="token string">'/pages/pageB'</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token string">'/pages/pageA'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 后面的逻辑在页面跳转之后，不会再生效</span>
<span class="token function">navigateTo</span><span class="token punctuation">(</span><span class="token punctuation">{</span>url<span class="token operator">:</span> <span class="token string">'/pages/pageC'</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token string">'/pages/pageA'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><h2 id="跳转传参"><a href="#跳转传参" class="header-anchor">#</a> 跳转传参</h2> <p>小程序提供的跳转相关 API，需要在 url 后面添加参数的方式来传参，但有些时候我们不仅仅需要携带简单的字符串或者数字，我们还可能需要携带一个较大的对象数据。那么这种情况下，由于小程序页面切换依然在同一个 JsCore 上下文，我们可以通过共享对象的方式来传递。</p> <p>共享对象需要在公共库中存储一个当前跳转的传参内容，同时为了避免页面同时跳转导致传参内容不匹配，我们可以通过一个随机 ID 的方式来标记：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">getRandomId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 时间戳（9位） + 随机串（10位）</span>
  <span class="token keyword">return</span> <span class="token punctuation">(</span>Date<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span> <span class="token operator">+</span> Math<span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>跳转的时候，我们可以根据 url 传参的方式，还是共享对象传参的方式，来进行不同的判断处理：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">let</span> globalPageParams <span class="token operator">=</span> <span class="token keyword">undefined</span><span class="token punctuation">;</span> <span class="token comment">// 全局页面跳转参数</span>
<span class="token keyword">let</span> globalPageParamsId<span class="token operator">:</span> any <span class="token operator">=</span> <span class="token keyword">undefined</span><span class="token punctuation">;</span> <span class="token comment">// 全局页面跳转参数Id，用于标识某一次跳转的数据</span>

<span class="token comment">// 跳转时参数处理</span>
<span class="token keyword">function</span> <span class="token function">mangeUrl</span><span class="token punctuation">(</span><span class="token parameter">url<span class="token punctuation">,</span> options</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> <span class="token punctuation">{</span> urlParams<span class="token punctuation">,</span> pageParams <span class="token punctuation">}</span> <span class="token operator">=</span> options<span class="token punctuation">;</span>

  <span class="token comment">// url参数处理</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>urlParams<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    url <span class="token operator">=</span> <span class="token function">addUrlParams</span><span class="token punctuation">(</span>url<span class="token punctuation">,</span> urlParams<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token comment">// 页面参数处理</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>pageParams<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    globalPageParams <span class="token operator">=</span> <span class="token function">objectCopy</span><span class="token punctuation">(</span>pageParams<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 获取随机 ID</span>
    globalPageParamsId <span class="token operator">=</span> <span class="token function">getRandomId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 将随机 ID 带入 url 参数中，可用来获取全局参数</span>
    url <span class="token operator">=</span> <span class="token function">addUrlParams</span><span class="token punctuation">(</span>url<span class="token punctuation">,</span> <span class="token punctuation">{</span> randomid<span class="token operator">:</span> globalPageParamsId <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    globalPageParams <span class="token operator">=</span> <span class="token keyword">undefined</span><span class="token punctuation">;</span>
    globalPageParamsId <span class="token operator">=</span> <span class="token keyword">undefined</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> url<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这样，我们的跳转方法可以这么处理：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">/**
 * 跳转到页面
 * @param {object} url 要跳转的页面地址
 * @param {object} options 要携带的参数信息
 * @param {object} originPageUrl 原始页面地址，用于判断来源是否符合
 */</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">navigateTo</span><span class="token punctuation">(</span><span class="token parameter">url<span class="token punctuation">,</span> options <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">,</span> originPageUrl</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  url <span class="token operator">=</span> <span class="token function">mangeUrl</span><span class="token punctuation">(</span>url<span class="token punctuation">,</span> options<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 不符合源页面条件则不跳转</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">matchOriginPath</span><span class="token punctuation">(</span>originPageUrl<span class="token operator">!</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    logger<span class="token punctuation">.</span><span class="token constant">RUN</span><span class="token punctuation">(</span><span class="token string">&quot;navigateTo&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;originPageUrl != currentPage, return&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  wx<span class="token punctuation">.</span><span class="token function">navigateTo</span><span class="token punctuation">(</span><span class="token punctuation">{</span> url <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><h2 id="结合-component-自动取参"><a href="#结合-component-自动取参" class="header-anchor">#</a> 结合 Component 自动取参</h2> <p>我们有介绍过如何使用 Component 来开发页面，使用 Component 有几个好处：</p> <ol><li>可以通过 Behavior 来拓展组件的通用能力。</li> <li>可以直接通过定义 properties 来获取页面参数。</li></ol> <blockquote><p>页面如何使用 Behavior
看看<a href="https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.html" target="_blank" rel="noopener noreferrer">官方文档<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>：事实上，小程序的页面也可以视为自定义组件。因而，页面也可以使用<code>Component</code>构造器构造，拥有与普通组件一样的定义段与实例方法。但此时要求对应<code>json</code>文件中包含<code>usingComponents</code>定义段。</p></blockquote> <p>这里配合跳转传参，我们可以省略很多的逻辑。例如我们有一个结果页面，页面展示直接从 url 中取值（如果使用 Page 的 query 方式获取参数，需要自己进行  decodeURIComponent 才能使用，而使用组件的 properties 则不需要）：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token function">Component</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token comment">// 其他配置省略</span>
  properties<span class="token operator">:</span> <span class="token punctuation">{</span>
    type<span class="token operator">:</span> String<span class="token punctuation">,</span>  <span class="token comment">// 结果类型，成功-success，失败-warn</span>
    title<span class="token operator">:</span> String<span class="token punctuation">,</span> <span class="token comment">// 主要文案</span>
    info<span class="token operator">:</span> String <span class="token comment">// 辅助文案</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>我们这样进行跳转：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token function">navigateTo</span><span class="token punctuation">(</span><span class="token string">&quot;/pages/result/result&quot;</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
  <span class="token comment">// 直接带入参数，result组件可通过properties直接拿到</span>
  urlParams<span class="token operator">:</span> <span class="token punctuation">{</span>
    type<span class="token operator">:</span> <span class="token string">&quot;success&quot;</span><span class="token punctuation">,</span>
    title<span class="token operator">:</span> <span class="token string">&quot;操作成功&quot;</span><span class="token punctuation">,</span>
    info<span class="token operator">:</span> <span class="token string">&quot;成功就是这么简单&quot;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>则可以直接在模板中显示：</p> <div class="language-html extra-class"><pre class="language-html"><code><span class="token comment">&lt;!-- 使用的 weui 组件库 --&gt;</span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>view</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>page<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>weui-msg</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>{{type}}<span class="token punctuation">&quot;</span></span> <span class="token attr-name">title</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>{{title}}<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>view</span> <span class="token attr-name">slot</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>desc<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>{{info}}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>view</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>weui-msg</span><span class="token punctuation">&gt;</span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>view</span><span class="token punctuation">&gt;</span></span>
</code></pre></div><p>如果是通过页面传参的方式，则需要通过随机 ID 来获取对应的参数：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// 通过随机 ID 获取对应参数</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">getPageParams</span><span class="token punctuation">(</span><span class="token parameter">randomId</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>globalPageParamsId <span class="token operator">===</span> randomId<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> globalPageParams <span class="token operator">||</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>组件中可以通过 properties 来获取随机 ID，然后获取对应参数：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token function">Component</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token comment">// 其他配置省略</span>
  properties<span class="token operator">:</span> <span class="token punctuation">{</span>
    randomid<span class="token operator">:</span> String<span class="token punctuation">,</span>  <span class="token comment">// 随机 ID</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  methods<span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">onLoad</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 获取参数</span>
      <span class="token keyword">const</span> params <span class="token operator">=</span> <span class="token function">getPageParams</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>data<span class="token punctuation">.</span>randomid<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 处理参数</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>具体的代码实现，可参考项目代码：<a href="https://github.com/godbasin/wxapp-typescript-demo" target="_blank" rel="noopener noreferrer">wxapp-typescript-demo<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>。</p> <h2 id="参考"><a href="#参考" class="header-anchor">#</a> 参考</h2> <ul><li><a href="https://developers.weixin.qq.com/ebook?action=get_post_info&amp;docid=000a64a29c48b0eb0086f161b5940a" target="_blank" rel="noopener noreferrer">7.2 页面层级准备<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li> <li><a href="https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.html" target="_blank" rel="noopener noreferrer">Component构造器<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li> <li><a href="https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/behaviors.html" target="_blank" rel="noopener noreferrer">behaviors<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul> <h1 id="结束语"><a href="#结束语" class="header-anchor">#</a> 结束语</h1> <p>使用自定义组件的方式来开发页面，简直不能太赞啦。通过 Behavior 来各种拓展组件的能力，同时还能简化一些取参的逻辑，还是特别方便的。</p></div> <!----> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/godbasin/front-end-playground/edit/sourcecode/docs/wxapp/wxapp-technique/wxapp-navigate.md" target="_blank" rel="noopener noreferrer">帮阿猪改善此页面！</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <!----> <blockquote>部分文章中使用了一些网站的截图，如果涉及侵权，请告诉我删一下谢谢~</blockquote> <div style="margin-top:30px;"><div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-sm-0 el-col-md-2 el-col-lg-4" style="padding-left:10px;padding-right:10px;display:block;"><div style="width:1px;height:1px;"></div></div> <div class="el-col el-col-24 el-col-sm-24 el-col-md-18 el-col-lg-16" style="padding-left:10px;padding-right:10px;"><div class="el-card box-card is-always-shadow"><div class="el-card__header"><div class="clearfix"><span>温馨提示喵</span></div></div><div class="el-card__body"> <div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="el-image"><div class="image-slot"><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/loading.gif" style="width:100%;"></div><!----></div></div> <div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="copyright-text"><div>本文版权归作者所有，欢迎转载，但未经作者同意必须保留此段声明，且在文章页面明显位置给出原文连接，否则保留追究法律责任的权利。</div> <div>出处：被删的前端游乐场</div> <div>作者：<a href="https://github.com/godbasin" target="_blank">被删</a></div></div></div></div></div></div></div></div></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/front-end-playground/wxapp/wxapp-technique/wxapp-logs.html" class="prev">
          小程序奇技淫巧之日志能力
        </a></span> <span class="next"><a href="/front-end-playground/wxapp/wxapp-latest/wxapp-latest-20190114.html">
          小程序开发月刊第一期（20190114）
        </a>
        →
      </span></p></div>  <div class="gitalk-container theme-default-content"><div id="gitalk-container" class="content"></div></div></main> <div id="kitty-container"><span><div role="tooltip" id="el-popover-4863" aria-hidden="true" class="el-popover el-popper" style="width:undefinedpx;display:none;"><!----><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/2code2.jpg" class="image"> <div class="text">牡羊猪的猫粮罐</div> </div><span class="el-popover__reference-wrapper"><div id="kitty" style="background:url(https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/kitty2.svg);"></div></span></span> <div class="el-dialog__wrapper" style="display:none;"><div role="dialog" aria-modal="true" aria-label="牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）" class="el-dialog" style="margin-top:15vh;"><div class="el-dialog__header"><span class="el-dialog__title">牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）</span><button type="button" aria-label="Close" class="el-dialog__headerbtn"><i class="el-dialog__close el-icon el-icon-close"></i></button></div><!----><!----></div></div></div></div><div class="global-ui"></div></div>
    <script src="/front-end-playground/assets/js/app.1e2670bf.js" defer></script><script src="/front-end-playground/assets/js/2.38d016d1.js" defer></script><script src="/front-end-playground/assets/js/3.e3f029cb.js" defer></script><script src="/front-end-playground/assets/js/186.32496fdc.js" defer></script>
  </body>
</html>
